<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PDF编辑 - Snapan网盘</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.14.305/pdf.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.14.305/pdf.worker.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/pdf-lib@1.17.1/dist/pdf-lib.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        :root {
            --primary: #667eea;
            --primary-dark: #5a6edb;
            --secondary: #764ba2;
            --secondary-light: rgba(118, 75, 162, 0.1);
            --text-primary: #333;
            --text-secondary: #666;
            --text-tertiary: #999;
            --border: #e0e0e0;
            --bg-light: #f5f7fa;
            --white: #fff;
            --shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
            --radius: 8px;
            --transition: all 0.25s ease;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background-color: var(--bg-light);
            color: var(--text-primary);
            overflow: hidden;
            height: 100vh;
            line-height: 1.5;
        }

        .container {
            display: flex;
            height: 100%;
        }

        .sidebar {
            width: 240px;
            background: var(--white);
            border-right: 1px solid var(--border);
            display: flex;
            flex-direction: column;
            box-shadow: var(--shadow);
            z-index: 10;
        }

        .logo-section {
            padding: 20px 16px;
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            color: var(--white);
        }

        .logo {
            display: flex;
            align-items: center;
            gap: 12px;
            font-size: 18px;
            font-weight: 600;
        }

        .logo-icon {
            width: 32px;
            height: 32px;
            background: rgba(255, 255, 255, 0.2);
            border-radius: var(--radius);
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .storage-info {
            font-size: 12px;
            margin-top: 12px;
            padding-top: 10px;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
            opacity: 0.9;
        }

        .nav-section {
            padding: 16px 0;
        }

        .nav-title {
            font-size: 12px;
            text-transform: uppercase;
            color: var(--text-tertiary);
            padding: 0 16px 8px;
            letter-spacing: 0.5px;
        }

        .nav-item {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 10px 16px;
            color: var(--text-secondary);
            text-decoration: none;
            transition: var(--transition);
            position: relative;
        }

        .nav-item:hover {
            background-color: rgba(102, 126, 234, 0.08);
            color: var(--primary);
        }

        .nav-item.active {
            background-color: var(--secondary-light);
            color: var(--secondary);
            font-weight: 500;
        }

        .nav-item.active::before {
            content: '';
            position: absolute;
            left: 0;
            top: 0;
            height: 100%;
            width: 3px;
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
        }

        .nav-icon {
            width: 20px;
            text-align: center;
        }

        .main-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            margin: 12px;
            background: var(--white);
            border-radius: var(--radius);
            box-shadow: var(--shadow);
            overflow: hidden;
        }

        .pdf-toolbar {
            padding: 14px 20px;
            border-bottom: 1px solid var(--border);
        }

        .pdf-path {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 13px;
            color: var(--text-tertiary);
            margin-bottom: 12px;
        }

        .pdf-path-item {
            color: var(--text-tertiary);
            text-decoration: none;
        }

        .pdf-path-item:hover {
            color: var(--primary);
            text-decoration: underline;
        }

        .pdf-path-separator {
            font-size: 11px;
        }

        .pdf-title-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .pdf-title {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .pdf-icon {
            width: 36px;
            height: 36px;
            background: linear-gradient(135deg, #d299c2 0%, #fef9d7 100%);
            border-radius: var(--radius);
            display: flex;
            align-items: center;
            justify-content: center;
            color: var(--secondary);
            font-size: 18px;
        }

        .pdf-name {
            font-size: 16px;
            font-weight: 600;
            max-width: 300px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .pdf-actions {
            display: flex;
            gap: 10px;
        }

        .action-btn {
            display: flex;
            align-items: center;
            gap: 6px;
            padding: 8px 14px;
            border-radius: var(--radius);
            border: 1px solid var(--border);
            background: var(--white);
            color: var(--text-secondary);
            font-size: 13px;
            cursor: pointer;
            transition: var(--transition);
        }

        .action-btn:hover {
            background-color: var(--bg-light);
            border-color: rgba(102, 126, 234, 0.3);
        }

        .action-btn.primary {
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            color: var(--white);
            border: none;
            box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
        }

        .action-btn.primary:hover {
            background: linear-gradient(135deg, var(--primary-dark) 0%, #6a4392 100%);
        }

        .pdf-edit-container {
            display: flex;
            flex: 1;
            overflow: hidden;
        }

        .edit-tools-panel {
            width: 60px;
            background: var(--white);
            border-right: 1px solid var(--border);
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 16px 0;
            gap: 16px;
        }

        .edit-tool {
            width: 40px;
            height: 40px;
            border-radius: var(--radius);
            display: flex;
            align-items: center;
            justify-content: center;
            color: var(--text-secondary);
            cursor: pointer;
            transition: var(--transition);
            position: relative;
        }

        .edit-tool:hover {
            background-color: rgba(102, 126, 234, 0.08);
            color: var(--primary);
        }

        .edit-tool.active {
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            color: var(--white);
            box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
        }

        .tool-tooltip {
            position: absolute;
            left: 50px;
            top: 50%;
            transform: translateY(-50%);
            background: rgba(0, 0, 0, 0.8);
            color: var(--white);
            padding: 4px 10px;
            border-radius: 4px;
            font-size: 12px;
            white-space: nowrap;
            opacity: 0;
            visibility: hidden;
            transition: var(--transition);
            z-index: 100;
        }

        .edit-tool:hover .tool-tooltip {
            opacity: 1;
            visibility: visible;
        }

        .pdf-preview-area {
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            background: var(--bg-light);
        }

        .preview-control-bar {
            padding: 10px 20px;
            background: var(--white);
            border-bottom: 1px solid var(--border);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .page-nav {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .nav-btn {
            display: flex;
            align-items: center;
            gap: 4px;
            padding: 4px 10px;
            background: transparent;
            border: none;
            color: var(--text-secondary);
            font-size: 13px;
            cursor: pointer;
            border-radius: 4px;
            transition: var(--transition);
        }

        .nav-btn:hover {
            background-color: rgba(102, 126, 234, 0.08);
            color: var(--primary);
        }

        .page-info {
            font-size: 13px;
            color: var(--text-secondary);
        }

        .preview-settings {
            display: flex;
            align-items: center;
            gap: 16px;
        }

        .zoom-control {
            display: flex;
            align-items: center;
            background: var(--white);
            border: 1px solid var(--border);
            border-radius: 4px;
            overflow: hidden;
        }

        .zoom-btn {
            width: 30px;
            height: 30px;
            border: none;
            background: transparent;
            color: var(--text-secondary);
            cursor: pointer;
            transition: var(--transition);
        }

        .zoom-btn:hover {
            background-color: rgba(102, 126, 234, 0.08);
            color: var(--primary);
        }

        .zoom-value {
            width: 40px;
            text-align: center;
            font-size: 13px;
            color: var(--text-secondary);
            border-left: 1px solid var(--border);
            border-right: 1px solid var(--border);
            padding: 0 4px;
        }

        .view-mode {
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .mode-btn {
            padding: 4px 10px;
            background: var(--white);
            border: 1px solid var(--border);
            border-radius: 4px;
            color: var(--text-secondary);
            font-size: 13px;
            cursor: pointer;
            transition: var(--transition);
        }

        .mode-btn:hover {
            background-color: rgba(102, 126, 234, 0.08);
            color: var(--primary);
        }

        .mode-btn.active {
            background-color: var(--secondary-light);
            color: var(--secondary);
            border-color: rgba(118, 75, 162, 0.2);
        }

        .preview-content {
            flex: 1;
            overflow: auto;
            display: flex;
            justify-content: center;
            align-items: flex-start;
            padding: 20px;
        }

        #pdfContainer {
            background: white;
            box-shadow: var(--shadow);
            border-radius: var(--radius);
        }

        #pdfCanvas {
            display: block;
        }

        .property-panel {
            width: 0;
            background: var(--white);
            border-left: 1px solid var(--border);
            overflow: hidden;
            transition: width 0.3s ease;
        }

        .property-panel.show {
            width: 300px;
            overflow-y: auto;
        }

        .panel-header {
            padding: 16px 20px;
            border-bottom: 1px solid var(--border);
        }

        .panel-title {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 4px;
        }

        .panel-subtitle {
            font-size: 12px;
            color: var(--text-tertiary);
        }

        .property-group {
            padding: 16px 20px;
            border-bottom: 1px solid var(--border);
        }

        .group-title {
            font-size: 13px;
            font-weight: 600;
            margin-bottom: 12px;
            color: var(--text-primary);
        }

        .property-item {
            margin-bottom: 14px;
        }

        .property-label {
            display: block;
            font-size: 12px;
            color: var(--text-tertiary);
            margin-bottom: 6px;
        }

        .property-input {
            width: 100%;
            padding: 8px 10px;
            border: 1px solid var(--border);
            border-radius: 4px;
            font-size: 13px;
            transition: var(--transition);
        }

        .property-input:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
        }

        .floating-toolbar {
            position: absolute;
            background: var(--white);
            border-radius: var(--radius);
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
            padding: 6px;
            display: none;
            z-index: 100;
        }

        .floating-toolbar.show {
            display: flex;
            gap: 4px;
        }

        .floating-btn {
            width: 32px;
            height: 32px;
            border: none;
            background: transparent;
            border-radius: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: var(--text-secondary);
            cursor: pointer;
            transition: var(--transition);
        }

        .floating-btn:hover {
            background-color: rgba(102, 126, 234, 0.08);
            color: var(--primary);
        }

        .toast {
            position: fixed;
            bottom: 30px;
            left: 50%;
            transform: translateX(-50%) translateY(100px);
            background: rgba(0, 0, 0, 0.8);
            color: var(--white);
            padding: 10px 16px;
            border-radius: 4px;
            font-size: 14px;
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
            z-index: 1000;
            transition: transform 0.3s ease;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .toast.show {
            transform: translateX(-50%) translateY(0);
        }

        .toast.success {
            background: rgba(76, 175, 80, 0.9);
        }

        .toast.error {
            background: rgba(244, 67, 54, 0.9);
        }

        #statusMsg {
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 8px 16px;
            border-radius: 4px;
            font-size: 14px;
            z-index: 1000;
        }

        #pdfFileInput {
            display: none;
        }
    </style>
</head>
<body>
<div id="statusMsg">请加载PDF文件开始编辑</div>

<div class="container">
    <div class="sidebar">
        <div class="logo-section">
            <div class="logo">
                <div class="logo-icon">☁️</div>
                <span>Snapan</span>
            </div>
            <div class="storage-info">已使用 2.1GB / 10GB</div>
        </div>

        <div class="nav-section">
            <div class="nav-title">主要功能</div>
            <a href="#" class="nav-item">
                <div class="nav-icon"><i class="fas fa-home"></i></div>
                <div>首页</div>
            </a>
            <a href="#" class="nav-item">
                <div class="nav-icon"><i class="fas fa-upload"></i></div>
                <div>传输</div>
            </a>
            <a href="#" class="nav-item">
                <div class="nav-icon"><i class="fas fa-sync-alt"></i></div>
                <div>同步</div>
            </a>
            <a href="#" class="nav-item active">
                <div class="nav-icon"><i class="fas fa-edit"></i></div>
                <div>PDF编辑</div>
            </a>
            <a href="#" class="nav-item">
                <div class="nav-icon"><i class="fas fa-comments"></i></div>
                <div>消息</div>
            </a>
        </div>

        <div class="nav-section">
            <div class="nav-title">文档工具</div>
            <a href="#" class="nav-item">
                <div class="nav-icon"><i class="fas fa-file-pdf"></i></div>
                <div>PDF转换</div>
            </a>
            <a href="#" class="nav-item">
                <div class="nav-icon"><i class="fas fa-file-word"></i></div>
                <div>文档合并</div>
            </a>
            <a href="#" class="nav-item">
                <div class="nav-icon"><i class="fas fa-lock"></i></div>
                <div>加密解密</div>
            </a>
        </div>
    </div>

    <div class="main-content">
        <div class="pdf-toolbar">
            <div class="pdf-path">
                <a href="#" class="pdf-path-item">首页</a>
                <span class="pdf-path-separator">/</span>
                <a href="#" class="pdf-path-item">我的文件</a>
                <span class="pdf-path-separator">/</span>
                <a href="#" class="pdf-path-item">文档</a>
            </div>

            <div class="pdf-title-bar">
                <div class="pdf-title">
                    <div class="pdf-icon"><i class="fas fa-file-pdf"></i></div>
                    <div class="pdf-name">未选择文件</div>
                </div>

                <div class="pdf-actions">
                    <button class="action-btn" id="openLocalBtn">
                        <i class="fas fa-file-pdf"></i>
                        <span>打开本地文件</span>
                    </button>
                    <input type="file" id="pdfFileInput" accept=".pdf">
                    <button class="action-btn" id="saveBtn">
                        <i class="fas fa-save"></i>
                        <span>保存</span>
                    </button>
                    <button class="action-btn" id="saveAsBtn">
                        <i class="fas fa-file-export"></i>
                        <span>另存为</span>
                    </button>
                    <button class="action-btn" id="shareBtn">
                        <i class="fas fa-share-alt"></i>
                        <span>分享</span>
                    </button>
                    <button class="action-btn" id="downloadBtn">
                        <i class="fas fa-download"></i>
                        <span>下载</span>
                    </button>
                    <button class="action-btn primary" id="doneBtn">
                        <i class="fas fa-check"></i>
                        <span>完成编辑</span>
                    </button>
                </div>
            </div>
        </div>

        <div class="pdf-edit-container">
            <div class="edit-tools-panel">
                <div class="edit-tool" id="selectTool">
                    <i class="fas fa-mouse-pointer"></i>
                    <span class="tool-tooltip">选择工具</span>
                </div>
                <div class="edit-tool" id="textTool">
                    <i class="fas fa-font"></i>
                    <span class="tool-tooltip">文本工具</span>
                </div>
                <div class="edit-tool" id="highlightTool">
                    <i class="fas fa-highlighter"></i>
                    <span class="tool-tooltip">高亮工具</span>
                </div>
                <div class="edit-tool" id="commentTool">
                    <i class="fas fa-comment"></i>
                    <span class="tool-tooltip">注释工具</span>
                </div>
                <div class="edit-tool" id="drawTool">
                    <i class="fas fa-pen"></i>
                    <span class="tool-tooltip">绘图工具</span>
                </div>
                <div class="edit-tool" id="imageTool">
                    <i class="fas fa-image"></i>
                    <span class="tool-tooltip">图片工具</span>
                </div>
                <div class="edit-tool" id="signatureTool">
                    <i class="fas fa-signature"></i>
                    <span class="tool-tooltip">签名工具</span>
                </div>
                <div class="edit-tool" id="propertiesTool">
                    <i class="fas fa-sliders-h"></i>
                    <span class="tool-tooltip">属性面板</span>
                </div>
            </div>

            <div class="pdf-preview-area">
                <div class="preview-control-bar">
                    <div class="page-nav">
                        <button class="nav-btn" id="prevPage">
                            <i class="fas fa-chevron-left"></i>
                            <span>上一页</span>
                        </button>
                        <div class="page-info">第 <span id="currentPageNum">1</span> 页，共 <span id="totalPages">0</span> 页</div>
                        <button class="nav-btn" id="nextPage">
                            <span>下一页</span>
                            <i class="fas fa-chevron-right"></i>
                        </button>
                    </div>

                    <div class="preview-settings">
                        <div class="zoom-control">
                            <button class="zoom-btn" id="zoomOut">
                                <i class="fas fa-minus"></i>
                            </button>
                            <div class="zoom-value" id="zoomLevel">100%</div>
                            <button class="zoom-btn" id="zoomIn">
                                <i class="fas fa-plus"></i>
                            </button>
                        </div>

                        <div class="view-mode">
                            <button class="mode-btn active" id="singlePageMode">单页</button>
                            <button class="mode-btn" id="continuousMode">连续</button>
                            <button class="mode-btn" id="twoPageMode">双页</button>
                        </div>
                    </div>
                </div>

                <div class="preview-content">
                    <div id="pdfContainer">
                        <canvas id="pdfCanvas"></canvas>
                    </div>
                </div>
            </div>

            <div class="property-panel" id="propertyPanel">
                <div class="panel-header">
                    <div class="panel-title">文档属性</div>
                    <div class="panel-subtitle">查看和修改文档信息</div>
                </div>

                <div class="property-group">
                    <div class="group-title">基本信息</div>
                    <div class="property-item">
                        <label class="property-label">文件名</label>
                        <input type="text" class="property-input" id="fileNameInput" value="未选择文件">
                    </div>
                    <div class="property-item">
                        <label class="property-label">创建日期</label>
                        <input type="text" class="property-input" value="--" disabled>
                    </div>
                    <div class="property-item">
                        <label class="property-label">修改日期</label>
                        <input type="text" class="property-input" value="--" disabled>
                    </div>
                    <div class="property-item">
                        <label class="property-label">文件大小</label>
                        <input type="text" class="property-input" value="--" disabled>
                    </div>
                </div>

                <div class="property-group">
                    <div class="group-title">文档设置</div>
                    <div class="property-item">
                        <label class="property-label">页面大小</label>
                        <select class="property-input">
                            <option>A4</option>
                            <option>Letter</option>
                            <option>Legal</option>
                        </select>
                    </div>
                    <div class="property-item">
                        <label class="property-label">方向</label>
                        <select class="property-input">
                            <option>纵向</option>
                            <option>横向</option>
                        </select>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="floating-toolbar" id="floatingToolbar">
    <button class="floating-btn" title="复制"><i class="fas fa-copy"></i></button>
    <button class="floating-btn" title="剪切"><i class="fas fa-cut"></i></button>
    <button class="floating-btn" title="粘贴"><i class="fas fa-paste"></i></button>
    <button class="floating-btn" title="删除"><i class="fas fa-trash"></i></button>
</div>

<div class="toast" id="toast">
    <i class="fas" id="toastIcon"></i>
    <span id="toastMessage"></span>
</div>

<script>
    // 核心变量（以pdf-editor.js为准）
    let pdfDoc = null;
    let currentPage = 1;
    let canvas = document.getElementById('pdfCanvas');
    let ctx = canvas.getContext('2d');
    let currentTool = null;
    let originalPdfBytes = null;
    let currentZoom = 100;
    let fileName = "未选择文件";

    // DOM元素
    const statusMsg = document.getElementById('statusMsg');
    const pdfFileInput = document.getElementById('pdfFileInput');
    const pdfNameEl = document.querySelector('.pdf-name');
    const fileNameInput = document.getElementById('fileNameInput');
    const currentPageNumEl = document.getElementById('currentPageNum');
    const totalPagesEl = document.getElementById('totalPages');

    // 初始化事件监听
    function init() {
        // pdf-editor核心工具事件
        document.getElementById('highlightTool').addEventListener('click', () => setTool('highlight'));
        document.getElementById('textTool').addEventListener('click', () => setTool('text'));
        document.getElementById('imageTool').addEventListener('click', () => setTool('image'));
        document.getElementById('saveBtn').addEventListener('click', savePdf);
        document.getElementById('saveAsBtn').addEventListener('click', savePdf);
        document.getElementById('pdfFileInput').addEventListener('change', handleFileSelect);
        document.getElementById('openLocalBtn').addEventListener('click', () => pdfFileInput.click());

        // 页面导航
        document.getElementById('prevPage').addEventListener('click', () => {
            if (currentPage > 1) {
                currentPage--;
                renderPage(currentPage);
            }
        });

        document.getElementById('nextPage').addEventListener('click', () => {
            if (currentPage < pdfDoc.numPages) {
                currentPage++;
                renderPage(currentPage);
            }
        });

        // 缩放控制
        document.getElementById('zoomIn').addEventListener('click', () => {
            if (currentZoom < 200) {
                currentZoom += 10;
                updateZoom();
            }
        });

        document.getElementById('zoomOut').addEventListener('click', () => {
            if (currentZoom > 50) {
                currentZoom -= 10;
                updateZoom();
            }
        });

        // 属性面板
        document.getElementById('propertiesTool').addEventListener('click', () => {
            document.getElementById('propertyPanel').classList.toggle('show');
        });

        // 完成编辑按钮
        document.getElementById('doneBtn').addEventListener('click', () => {
            if (confirm('确定要完成编辑并返回吗？未保存的更改将会丢失。')) {
                showToast('已完成编辑', 'success');
            }
        });

        // 下载按钮事件
        document.getElementById('downloadBtn').addEventListener('click', () => {
            if (pdfDoc) {
                downloadPdf();
            } else {
                showToast('请先打开PDF文件', 'error');
            }
        });
    }

    // 下载PDF文件
    function downloadPdf() {
        try {
            if (!pdfDoc) {
                showToast('没有可下载的PDF文件', 'error');
                return;
            }

            // 获取当前PDF的URL参数
            const urlParams = new URLSearchParams(window.location.search);
            const fileId = urlParams.get('fileId');
            
            if (fileId) {
                // 调用后端下载接口
                const downloadUrl = `/api/filebase/download/${fileId}`;
                const link = document.createElement('a');
                link.href = downloadUrl;
                link.download = `edited_${pdfDoc.getMetadata().title || 'document'}.pdf`;
                link.style.display = 'none';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                
                showToast('开始下载PDF文件', 'success');
            } else {
                showToast('无法获取文件ID', 'error');
            }
        } catch (error) {
            console.error('下载失败:', error);
            showToast('下载失败，请稍后重试', 'error');
        }
    }

    // 设置当前工具（以pdf-editor.js为准）
    function setTool(tool) {
        currentTool = tool;
        statusMsg.textContent = `当前工具：${tool}`;

        // 更新工具按钮状态
        document.querySelectorAll('.edit-tool').forEach(t => t.classList.remove('active'));
        document.getElementById(`${tool}Tool`).classList.add('active');
    }

    // 处理文件选择（以pdf-editor.js为准）
    async function handleFileSelect(event) {
        const file = event.target.files[0];
        if (!file) return;

        fileName = file.name;
        pdfNameEl.textContent = fileName;
        fileNameInput.value = fileName;
        statusMsg.textContent = '加载中...';

        const reader = new FileReader();
        reader.onload = async function (e) {
            originalPdfBytes = e.target.result;
            const loadingTask = pdfjsLib.getDocument({data: originalPdfBytes});
            pdfDoc = await loadingTask.promise;

            // 更新页面信息
            totalPagesEl.textContent = pdfDoc.numPages;
            currentPage = 1;
            currentPageNumEl.textContent = currentPage;

            renderPage(currentPage);
            statusMsg.textContent = `已加载：${file.name}`;
            showToast(`已加载：${file.name}`, 'success');
        };
        reader.readAsArrayBuffer(file);
    }

    // 渲染页面（以pdf-editor.js为准）
    async function renderPage(num) {
        const page = await pdfDoc.getPage(num);
        const viewport = page.getViewport({scale: currentZoom / 100});
        canvas.height = viewport.height;
        canvas.width = viewport.width;

        const renderContext = {canvasContext: ctx, viewport: viewport};
        await page.render(renderContext).promise;

        // 更新当前页码显示
        currentPageNumEl.textContent = num;

        // 设置画布点击事件（以pdf-editor.js为准）
        canvas.onclick = function (e) {
            if (currentTool === 'highlight') drawHighlight(e);
            else if (currentTool === 'text') addText(e);
            else if (currentTool === 'image') addImage(e);
        };
    }

    // 绘制高亮（以pdf-editor.js为准）
    function drawHighlight(e) {
        const rectSize = 80;
        ctx.fillStyle = 'rgba(255,255,0,0.5)';
        ctx.fillRect(e.offsetX, e.offsetY, rectSize, 20);
    }

    // 添加文本（以pdf-editor.js为准）
    function addText(e) {
        const text = prompt('请输入文字：');
        if (text) {
            ctx.font = '16px sans-serif';
            ctx.fillStyle = 'red';
            ctx.fillText(text, e.offsetX, e.offsetY);
        }
    }

    // 添加图片（以pdf-editor.js为准）
    function addImage(e) {
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = 'image/*';
        input.onchange = function (evt) {
            const imgFile = evt.target.files[0];
            const reader = new FileReader();
            reader.onload = function (r) {
                const img = new Image();
                img.onload = function () {
                    ctx.drawImage(img, e.offsetX, e.offsetY, 100, 100);
                };
                img.src = r.target.result;
            };
            reader.readAsDataURL(imgFile);
        };
        input.click();
    }

    // 保存PDF（以pdf-editor.js为准）
    async function savePdf() {
        if (!originalPdfBytes) {
            alert("请先加载一个 PDF 文件");
            return;
        }
        statusMsg.textContent = "正在保存...";

        // 获取当前画布内容作为图片
        const canvasDataUrl = canvas.toDataURL('image/png');
        const imageBytes = await fetch(canvasDataUrl).then(res => res.arrayBuffer());

        // 使用PDFLib处理PDF
        const pdfDocLib = await PDFLib.PDFDocument.load(originalPdfBytes);
        const pages = pdfDocLib.getPages();
        const firstPage = pages[currentPage - 1];

        // 将编辑内容绘制到PDF
        const pngImage = await pdfDocLib.embedPng(imageBytes);
        firstPage.drawImage(pngImage, {
            x: PDFLib.Point.zero(),
            y: PDFLib.Point.zero(),
            width: firstPage.getWidth(),
            height: firstPage.getHeight()
        });

        // 保存修改
        const newBytes = await pdfDocLib.save();
        const blob = new Blob([newBytes], {type: 'application/pdf'});
        const formData = new FormData();
        formData.append('file', blob, fileName);

        // 调用后端接口（以pdf-editor.js为准）
        $.ajax({
            url: '/api/pdf/save',
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            success: function (res) {
                statusMsg.textContent = "保存成功！";
                showToast("保存成功！", "success");
            },
            error: function () {
                statusMsg.textContent = "保存失败";
                showToast("保存失败", "error");
            }
        });
    }

    // 更新缩放
    function updateZoom() {
        document.getElementById('zoomLevel').textContent = `${currentZoom}%`;
        if (pdfDoc) {
            renderPage(currentPage);
        }
    }

    // 显示提示消息
    function showToast(message, type = 'info') {
        const toast = document.getElementById('toast');
        const toastIcon = document.getElementById('toastIcon');
        const toastMessage = document.getElementById('toastMessage');

        toastMessage.textContent = message;
        toastIcon.className = 'fas';

        switch(type) {
            case 'success':
                toastIcon.classList.add('fa-check-circle');
                toast.className = 'toast success';
                break;
            case 'error':
                toastIcon.classList.add('fa-exclamation-circle');
                toast.className = 'toast error';
                break;
            default:
                toastIcon.classList.add('fa-info-circle');
                toast.className = 'toast';
        }

        toast.classList.add('show');

        setTimeout(() => {
            toast.classList.remove('show');
        }, 3000);
    }

    // 初始化
    document.addEventListener('DOMContentLoaded', init);
</script>
</body>
</html>